#region    [自定义类-VS][20250106000000000][DoubleStackerConfirm]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GZ.DB.Entity.wcs_hy;
using GZ.DB.IRepository.wcs_hy;
using GZ.DB.Repository.wcs_hy;
using GZ.Common.Data;

namespace GZ.Projects.WCS_YB
{
    /// <summary>
    /// 双工位堆垛机任务确认反馈辅助类
    /// </summary>
    public class DoubleStackerConfirm
    {
        private Conn Conn = new Conn();
        private const string LAST_TASK_TYPE_REDIS_KEY = "MEM.TC01_LastTaskType"; // Redis中记录上次执行任务类型的键
        /// <summary>
        /// 设置双工位LAST反馈
        /// </summary>
        /// <param name="num">堆垛机编号</param>
        /// <returns>处理结果</returns>
        public TaskConfirmResult SetLastFeedback(string num)
        {
            string suffixName = $"TC{num}";
            string groupName = $"TC{num}.feedbackClear_{num}";
            string srmNo = $"TC{num}.wcs_srmNo";
            string commandType = $"TC{num}.wcs_commandType";
            string confirmSignal1 = $"TC{num}.wcs_confirmSignal1";
            string confirmSignal2 = $"TC{num}.wcs_confirmSignal2";
            string setQueue = $"TC{num}Queue";
            string setLast1 = $"{suffixName}.plc_taskStatus1_LAST";
            string setLast2 = $"{suffixName}.plc_taskStatus2_LAST";
            string msg = $"\r\n[双工位堆垛机任务完成反馈LAST更新[{suffixName}]]：Start{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            bool result = false;
            DateTime startTime = DateTime.Now;
            
            try
            {
                // 双工位LAST值置位
                GZ.Modular.Redis.WriteGroupEntity group = new GZ.Modular.Redis.WriteGroupEntity
                {
                    groupName = groupName,
                    queueStatus = 1,
                    queueTime = DateTime.Now,
                    writeList = new List<GZ.Modular.Redis.ParamData>
                    {
                        new GZ.Modular.Redis.ParamData { paramName = srmNo, paramValue = "0" },
                        new GZ.Modular.Redis.ParamData { paramName = commandType, paramValue = "0" },
                        new GZ.Modular.Redis.ParamData { paramName = confirmSignal1, paramValue = "0" },
                        new GZ.Modular.Redis.ParamData { paramName = confirmSignal2, paramValue = "0" }
                    }
                };
                
                // 同时设置两个工位的LAST状态
                bool result1 = Conn.YBRedis.SetQueue(group, setQueue, setLast1, "0");
                bool result2 = Conn.YBRedis.SetQueue(group, setQueue, setLast2, "0");
                result = result1 && result2;
            }
            catch (Exception ex)
            {
                msg += $"\r\n\t[Error]{ex}";
                result = false;
            }

            msg += $"\r\n\t[双工位堆垛机任务完成反馈LAST更新[{suffixName}]]：End{DateTime.Now:yyyy/MM/dd HH:mm:ss}，耗时：{(DateTime.Now - startTime).TotalMilliseconds}ms，结果：{result}";
            return new TaskConfirmResult(result, msg);
        }

        /// <summary>
        /// 双工位交互反馈
        /// </summary>
        /// <param name="num">堆垛机编号</param>
        /// <returns>处理结果</returns>
        public TaskConfirmResult InteractionFeedback(string num)
        {
            string suffixName = $"TC{num}";
            string msg = $"\r\n[双工位堆垛机任务交互反馈[{suffixName}]]：Start{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            DateTime startTime = DateTime.Now;
            bool isSuccess = true;
            
            try
            {
                // 获取双工位任务ID
                string plcTaskId1Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId1");
                string plcTaskId2Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId2");
                
                IStackerTaskRepository stackerRepo = new StackerTaskRepository();
                IMainMissionRepository mainMissionRepo = new MainMissionRepository();
                DBOpeation dbOpeation = new DBOpeation();

                // 查找双工位任务
                var stackerTasks = stackerRepo.FindList(t =>
                    (t.TaskState == "Send" || t.TaskState == "Doing") && 
                    t.DeviceNo == suffixName &&
                    (t.DeviceTaskNo == plcTaskId1Value || t.DeviceTaskNo == plcTaskId2Value))
                    .OrderByDescending(t => t.CreateTime).ToList();

                if (stackerTasks.Count >= 1)
                {
                    msg += $"\r\n\t找到{stackerTasks.Count}个双工位任务，开始更新状态";
                    
                    foreach (var stackerTask in stackerTasks)
                    {
                        var mainEntity = mainMissionRepo.FindList(t =>
                            (t.MissionState == "Send" || t.MissionState == "Doing") &&
                            t.device_task_no == stackerTask.DeviceTaskNo && 
                            t.tray_code == stackerTask.TrayCode)
                            .OrderByDescending(t => t.CreateTime).FirstOrDefault();

                        if (mainEntity != null)
                        {
                            // 更新任务状态为Doing
                            stackerTask.TaskState = "Doing";
                            stackerTask.TaskStartTime = DateTime.Now;
                            stackerTask.LastUpdatedTime = DateTime.Now;

                            mainEntity.MissionState = "Doing";
                            mainEntity.MissionEndTime = DateTime.Now;
                            mainEntity.LastUpdatedTime = DateTime.Now;
                            
                            bool result = dbOpeation.UpdateStackerAndMainTask(stackerTask, mainEntity, out string err);
                            if (result)
                            {
                                msg += $"\r\n\t更新任务{stackerTask.DeviceTaskNo}成功{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}";
                            }
                            else
                            {
                                msg += $"\r\n\t更新任务{stackerTask.DeviceTaskNo}失败，{err}{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}";
                                isSuccess = false;
                            }
                        }
                        else
                        {
                            msg += $"\r\n\t未找到任务{stackerTask.DeviceTaskNo}对应的主任务";
                            isSuccess = false;
                        }
                    }
                    
                    // 清除任务信号
                    if (isSuccess)
                    {
                        bool clearTaskResult = new StackerSendToRedis().ClearTask_DoubleStation(num, "0", "0", "0", out string ermsg);
                        msg += $"\r\n\t双工位下发点位清零结果:{clearTaskResult}{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}";
                        if (!clearTaskResult)
                        {
                            isSuccess = false;
                            msg += $"\r\n\t清零失败：{ermsg}";
                        }
                    }
                }
                else
                {
                    msg += $"\r\n\t[双工位堆垛机信息异常]：未找到对应的双工位任务信息";
                    isSuccess = false;
                }
            }
            catch (Exception ex)
            {
                msg += $"\r\n\t[Error]{ex}";
                isSuccess = false;
            }

            msg += $"\r\n\t[EndTime]{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            msg += $"\r\n\t[SpanTime]{(int)(DateTime.Now - startTime).TotalMilliseconds}ms";
            msg += $"\r\n[双工位堆垛机任务交互反馈[{suffixName}]]End";
            return new TaskConfirmResult(isSuccess, msg);
        }

        /// <summary>
        /// 双工位正常完成反馈
        /// </summary>
        /// <param name="num">堆垛机编号</param>
        /// <returns>处理结果</returns>
        public TaskConfirmResult NormalFinishFeedback(string num)
        {
            string suffixName = $"TC{num}";
            string msg = $"\r\n[[{suffixName}]双工位任务正常完成处理]：Start{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            DateTime startTime = DateTime.Now;
            bool isSuccess = true;
            
            try
            {
                // 获取双工位任务ID和MEM记录
                string plcTaskId1Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId1");
                string plcTaskId2Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId2");
                string memDeviceTaskNo1 = Conn.YBRedis.GetValue($"MEM.{suffixName}_DeviceTaskNo1");
                string memDeviceTaskNo2 = Conn.YBRedis.GetValue($"MEM.{suffixName}_DeviceTaskNo2");
                string memCont1 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont1");
                string memCont2 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont2");
                
                IStackerTaskRepository stackerRepo = new StackerTaskRepository();
                IMainMissionRepository mainMissionRepo = new MainMissionRepository();
                DBOpeation dbOpeation = new DBOpeation();

                // 处理工位1和工位2的任务
                var taskIds = new List<string>();
                if (!string.IsNullOrEmpty(plcTaskId1Value) && plcTaskId1Value != "0") taskIds.Add(plcTaskId1Value);
                if (!string.IsNullOrEmpty(plcTaskId2Value) && plcTaskId2Value != "0") taskIds.Add(plcTaskId2Value);
                if (!string.IsNullOrEmpty(memDeviceTaskNo1) && memDeviceTaskNo1 != "0") taskIds.Add(memDeviceTaskNo1);
                if (!string.IsNullOrEmpty(memDeviceTaskNo2) && memDeviceTaskNo2 != "0") taskIds.Add(memDeviceTaskNo2);

                var stackerTasks = stackerRepo.FindList(t =>
                    (t.TaskState == "Send" || t.TaskState == "Doing") && 
                    t.DeviceNo == suffixName &&
                    taskIds.Contains(t.DeviceTaskNo))
                    .OrderByDescending(t => t.CreateTime).ToList();

                if (stackerTasks.Count > 0)
                {
                    msg += $"\r\n\t找到{stackerTasks.Count}个需要完成的双工位任务";
                    
                    // 先清除任务信号
                    bool taskResult = new StackerSendToRedis().ClearTask_DoubleStation(num, "0", "3", "3", out string eMsg);
                    if (!taskResult)
                    {
                        msg += $"\r\n\t[双工位堆垛机信息完成异常]：指令清除结果失败{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}" + eMsg;
                        isSuccess = false;
                    }

                    foreach (var stackerTask in stackerTasks)
                    {
                        msg += $"\r\n\t处理任务：{stackerTask.DeviceTaskNo}，任务类型：{stackerTask.TaskType}";
                        
                        // 根据任务类型处理
                        if (stackerTask.TaskType == "ST_In" || stackerTask.TaskType == "ST_Move")
                        {
                            var mainEntity = mainMissionRepo.FindList(t =>
                                (t.MissionState == "Send" || t.MissionState == "Doing") &&
                                t.device_task_no == stackerTask.DeviceTaskNo &&
                                t.tray_code == stackerTask.TrayCode)
                                .OrderByDescending(t => t.CreateTime).FirstOrDefault();
                                
                            if (mainEntity != null)
                            {
                                // 更新为完成状态
                                stackerTask.TaskState = "Finish";
                                stackerTask.TaskEndTime = DateTime.Now;
                                stackerTask.LastUpdatedTime = DateTime.Now;

                                mainEntity.MissionState = "Finish";
                                mainEntity.MissionEndTime = DateTime.Now;
                                mainEntity.LastUpdatedTime = DateTime.Now;
                                
                                // 创建系统同步记录
                                SystemSynchronizationEntity systemSynchronization = new SystemSynchronizationEntity();
                                systemSynchronization.syn_direction = 1;
                                systemSynchronization.syn_status = 0;
                                systemSynchronization.ope_type = "CF";
                                systemSynchronization.order_no = mainEntity.order_no;
                                systemSynchronization.task_no = mainEntity.task_no;
                                systemSynchronization.ope_time = DateTime.Now;

                                bool resultMs = dbOpeation.UpdateMainAndStackInsertSysTask(mainEntity, stackerTask, systemSynchronization, out string err);
                                if (resultMs)
                                {
                                    msg += $"\r\n\t入库/移库任务{stackerTask.DeviceTaskNo}完成处理成功";
                                }
                                else
                                {
                                    msg += $"\r\n\t入库/移库任务{stackerTask.DeviceTaskNo}完成处理失败：{err}";
                                    isSuccess = false;
                                }
                            }
                        }
                        else if (stackerTask.TaskType == "ST_Out")
                        {
                            var mainEntity = mainMissionRepo.FindList(t =>
                                (t.MissionState == "Send" || t.MissionState == "Doing") &&
                                t.device_task_no == stackerTask.DeviceTaskNo &&
                                t.tray_code == stackerTask.TrayCode)
                                .OrderByDescending(t => t.CreateTime).FirstOrDefault();
                                
                            if (mainEntity != null)
                            {
                                // 出库任务：主任务状态改为Doing，堆垛机任务完成
                                mainEntity.MissionState = "Doing";
                                mainEntity.InteStationNo = stackerTask.ToLocalNo;
                                mainEntity.LastUpdatedTime = DateTime.Now;

                                stackerTask.TaskState = "Finish";
                                stackerTask.TaskEndTime = DateTime.Now;
                                stackerTask.LastUpdatedTime = DateTime.Now;

                                bool resultMt = dbOpeation.UpdateMainAndUpdateStack(mainEntity, stackerTask, out string err1);
                                if (resultMt)
                                {
                                    msg += $"\r\n\t出库任务{stackerTask.DeviceTaskNo}完成处理成功";
                                }
                                else
                                {
                                    msg += $"\r\n\t出库任务{stackerTask.DeviceTaskNo}完成处理失败：{err1}";
                                    isSuccess = false;
                                }
                            }
                        }
                    }
                    
                    // 清除MEM记录
                    if (isSuccess)
                    {
                                            StackMemTaskInfo("0", "0", "0", "0", "0", "0", "0", "0",num,"0");
                        msg += $"\r\n\t[双工位任务完成信号回复及清除MEM记录值]";
                    }
                }
                else
                {
                    msg += $"\r\n\t[双工位堆垛机信息完成异常]：未找到对应的双工位任务信息";
                    isSuccess = false;
                }
            }
            catch (Exception ex)
            {
                msg += $"\r\n\t[Error]{ex}";
                isSuccess = false;
            }

            msg += $"\r\n\t[EndTime]{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            msg += $"\r\n\t[SpanTime]{(int)(DateTime.Now - startTime).TotalMilliseconds}ms";
            msg += $"\r\n[{suffixName}]双工位任务正常完成]End";
            return new TaskConfirmResult(isSuccess, msg);
        }

        /// <summary>
        /// 双工位强制完成反馈
        /// </summary>
        /// <param name="num">堆垛机编号</param>
        /// <returns>处理结果</returns>
        public TaskConfirmResult ForceFinishFeedback(string num)
        {
            string suffixName = $"TC{num}";
            string msg = $"\r\n[[{suffixName}]双工位任务强制完成处理]：Start{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            DateTime startTime = DateTime.Now;
            bool isSuccess = true;

            try
            {
                // 获取双工位任务ID和MEM记录
                string plcTaskId1Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId1");
                string plcTaskId2Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId2");
                string memCont1 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont1");
                string memCont2 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont2");

                IStackerTaskRepository stackerRepo = new StackerTaskRepository();
                IMainMissionRepository mainMissionRepo = new MainMissionRepository();
                DBOpeation dbOpeation = new DBOpeation();

                // 处理工位1和工位2的任务
                var taskIds = new List<string>();
                if (!string.IsNullOrEmpty(plcTaskId1Value) && plcTaskId1Value != "0") taskIds.Add(plcTaskId1Value);
                if (!string.IsNullOrEmpty(plcTaskId2Value) && plcTaskId2Value != "0") taskIds.Add(plcTaskId2Value);
                if (!string.IsNullOrEmpty(memCont1) && memCont1 != "0") taskIds.Add(memCont1);
                if (!string.IsNullOrEmpty(memCont2) && memCont2 != "0") taskIds.Add(memCont2);

                var stackerTasks = stackerRepo.FindList(t =>
                    (t.TaskState == "Send" || t.TaskState == "Doing") &&
                    t.DeviceNo == suffixName &&
                    (taskIds.Contains(t.DeviceTaskNo) || taskIds.Contains(t.TrayCode)))
                    .OrderByDescending(t => t.CreateTime).ToList();

                if (stackerTasks.Count > 0)
                {
                    msg += $"\r\n\t找到{stackerTasks.Count}个需要强制完成的双工位任务";

                    foreach (var stackerTask in stackerTasks)
                    {
                        msg += $"\r\n\t强制完成任务：{stackerTask.DeviceTaskNo}";

                        // 更新堆垛机任务状态为完成
                        stackerTask.TaskState = "Finish";
                        stackerTask.TaskEndTime = DateTime.Now;
                        stackerTask.LastUpdatedTime = DateTime.Now;

                        bool result = dbOpeation.UpdateStackerTask(stackerTask, out string error);

                        // 如果是入库任务，主任务也要完成
                        if (stackerTask.TaskType == "ST_In")
                        {
                            var mainEntity = mainMissionRepo.FindList(t =>
                                (t.MissionState == "Send" || t.MissionState == "Doing") &&
                                t.task_no == stackerTask.TaskNo &&
                                t.tray_code == stackerTask.TrayCode)
                                .OrderByDescending(t => t.CreateTime).FirstOrDefault();

                            if (mainEntity != null)
                            {
                                mainEntity.MissionState = "Finish";
                                mainEntity.MissionEndTime = DateTime.Now;
                                mainEntity.LastUpdatedTime = DateTime.Now;

                                // 创建系统同步记录
                                SystemSynchronizationEntity systemSynchronization = new SystemSynchronizationEntity();
                                systemSynchronization.syn_direction = 1;
                                systemSynchronization.syn_status = 0;
                                systemSynchronization.ope_type = "CF";
                                systemSynchronization.order_no = mainEntity.order_no;
                                systemSynchronization.task_no = mainEntity.task_no;
                                systemSynchronization.ope_time = DateTime.Now;

                                bool resultMs = dbOpeation.UpdateMainAndInsertSyn(mainEntity, systemSynchronization, out string err);
                                if (resultMs)
                                {
                                    msg += $"\r\n\t入库任务{stackerTask.DeviceTaskNo}强制完成处理成功";
                                }
                                else
                                {
                                    msg += $"\r\n\t入库任务{stackerTask.DeviceTaskNo}强制完成处理失败：{err}";
                                    isSuccess = false;
                                }
                            }
                        }
                    }

                    // 清除任务信号
                    bool taskResult = new StackerSendToRedis().ClearTask_DoubleStation(num, "0", "5", "5", out string ermsg);
                                        StackMemTaskInfo("0", "0", "0", "0", "0", "0", "0", "0",num,"0");
                    msg += $"\r\n\t[双工位任务强制完成信号回复及清除MEM记录值]";

                    if (!taskResult)
                    {
                        msg += $"\r\n\t清除任务信号失败：{ermsg}";
                        isSuccess = false;
                    }
                }
                else
                {
                    // 即使没有找到任务，也要清除信号
                    bool taskFinishResult = new StackerSendToRedis().ClearTask_DoubleStation(num, "0", "5", "5", out string errormsg);
                        StackMemTaskInfo("0", "0", "0", "0", "0", "0", "0", "0",num,"0");
                    msg += $"\r\n\t获取双工位堆垛机任务异常，信号清除回复结果：{taskFinishResult}{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}";
                    if (!taskFinishResult)
                    {
                        isSuccess = false;
                        msg += $"\r\n\t清除信号失败：{errormsg}";
                    }
                }
            }
            catch (Exception ex)
            {
                msg += $"\r\n\t[Error]{ex}";
                isSuccess = false;
            }

            msg += $"\r\n\t[EndTime]{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            msg += $"\r\n\t[SpanTime]{(int)(DateTime.Now - startTime).TotalMilliseconds}ms";
            msg += $"\r\n[{suffixName}]双工位任务强制完成]End";
            return new TaskConfirmResult(isSuccess, msg);
        }

        /// <summary>
        /// 双工位取消任务反馈
        /// </summary>
        /// <param name="num">堆垛机编号</param>
        /// <returns>处理结果</returns>
        public TaskConfirmResult CancelFeedback(string num)
        {
            string suffixName = $"TC{num}";
            string msg = $"\r\n[[{suffixName}]双工位取消任务处理]：Start{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            DateTime startTime = DateTime.Now;
            bool isSuccess = true;

            try
            {
                // 获取双工位任务ID和MEM记录
                string plcTaskId1Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId1");
                string plcTaskId2Value = Conn.YBRedis.GetValue($"{suffixName}.plc_taskId2");
                string memCont1 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont1");
                string memCont2 = Conn.YBRedis.GetValue($"MEM.{suffixName}_Cont2");

                IStackerTaskRepository stackerRepo = new StackerTaskRepository();
                IMainMissionRepository mainMissionRepo = new MainMissionRepository();
                DBOpeation dbOpeation = new DBOpeation();

                // 处理工位1和工位2的任务
                var taskIds = new List<string>();
                if (!string.IsNullOrEmpty(plcTaskId1Value) && plcTaskId1Value != "0") taskIds.Add(plcTaskId1Value);
                if (!string.IsNullOrEmpty(plcTaskId2Value) && plcTaskId2Value != "0") taskIds.Add(plcTaskId2Value);
                if (!string.IsNullOrEmpty(memCont1) && memCont1 != "0") taskIds.Add(memCont1);
                if (!string.IsNullOrEmpty(memCont2) && memCont2 != "0") taskIds.Add(memCont2);

                var stackerTasks = stackerRepo.FindList(t =>
                    (t.TaskState == "Send" || t.TaskState == "Doing") &&
                    t.DeviceNo == suffixName &&
                    (taskIds.Contains(t.DeviceTaskNo) || taskIds.Contains(t.TrayCode)))
                    .OrderByDescending(t => t.CreateTime).ToList();

                if (stackerTasks.Count > 0)
                {
                    msg += $"\r\n\t找到{stackerTasks.Count}个需要取消的双工位任务";

                    foreach (var stackerTask in stackerTasks)
                    {
                        msg += $"\r\n\t取消任务：{stackerTask.DeviceTaskNo}";

                        // 更新堆垛机任务状态为取消
                        stackerTask.TaskState = "Cancel";
                        stackerTask.TaskEndTime = DateTime.Now;
                        stackerTask.LastUpdatedTime = DateTime.Now;

                        bool result = dbOpeation.UpdateStackerTask(stackerTask, out string error);

                        // 主任务也要取消
                        var mainEntity = mainMissionRepo.FindList(t =>
                            (t.MissionState == "Create" || t.MissionState == "Send" || t.MissionState == "Doing") &&
                            t.task_no == stackerTask.TaskNo &&
                            t.tray_code == stackerTask.TrayCode)
                            .OrderByDescending(t => t.CreateTime).FirstOrDefault();

                        if (mainEntity != null)
                        {
                            mainEntity.MissionState = "Cancel";
                            mainEntity.MissionEndTime = DateTime.Now;
                            mainEntity.LastUpdatedTime = DateTime.Now;

                            // 创建系统同步记录
                            SystemSynchronizationEntity systemSynchronization = new SystemSynchronizationEntity();
                            systemSynchronization.syn_direction = 1;
                            systemSynchronization.syn_status = 0;
                            systemSynchronization.ope_type = "CF";
                            systemSynchronization.order_no = mainEntity.order_no;
                            systemSynchronization.task_no = mainEntity.task_no;
                            systemSynchronization.ope_time = DateTime.Now;

                            bool resultMs = dbOpeation.UpdateMainAndInsertSyn(mainEntity, systemSynchronization, out string err);
                            if (resultMs)
                            {
                                msg += $"\r\n\t任务{stackerTask.DeviceTaskNo}取消处理成功";
                            }
                            else
                            {
                                msg += $"\r\n\t任务{stackerTask.DeviceTaskNo}取消处理失败：{err}";
                                isSuccess = false;
                            }
                        }
                        else
                        {
                            msg += $"\r\n\t获取任务{stackerTask.DeviceTaskNo}对应的主任务异常";
                            isSuccess = false;
                        }
                    }

                    // 清除任务信号
                    bool clearTaskResult = new StackerSendToRedis().ClearTask_DoubleStation(num, "12", "8", "8", out string ermsg);
                    StackMemTaskInfo("0", "0", "0", "0", "0", "0", "0", "0",num,"0");
                    msg += $"\r\n\t[双工位任务取消信号回复及清除MEM记录值]";

                    if (!clearTaskResult)
                    {
                        msg += $"\r\n\t清除任务信号失败：{ermsg}";
                        isSuccess = false;
                    }
                }
                else
                {
                    msg += $"\r\n\t获取双工位堆垛机任务异常，请检查状态或者条码{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff}";
                    isSuccess = false;
                }
            }
            catch (Exception ex)
            {
                msg += $"\r\n\t[Error]{ex}";
                isSuccess = false;
            }

            msg += $"\r\n\t[EndTime]{DateTime.Now:yyyy/MM/dd HH:mm:ss}";
            msg += $"\r\n\t[SpanTime]{(int)(DateTime.Now - startTime).TotalMilliseconds}ms";
            msg += $"\r\n[{suffixName}]双工位取消任务结束]End";
            return new TaskConfirmResult(isSuccess, msg);
        }

	/// <summary>
		/// 记录堆垛机任务的MEM数据到Redis，同时记录上次执行任务类型
		/// </summary>
		/// <param name="deviceTaskNo1">叉1设备任务号</param>
		/// <param name="contNum1">叉1托盘编码</param>
		/// <param name="curNum1">叉1当前位置</param>
		/// <param name="toNum1">叉1目标位置</param>
		/// <param name="deviceTaskNo2">叉2设备任务号（单叉时传空字符串）</param>
		/// <param name="contNum2">叉2托盘编码（单叉时传空字符串）</param>
		/// <param name="curNum2">叉2当前位置（单叉时传空字符串）</param>
		/// <param name="toNum2">叉2目标位置（单叉时传空字符串）</param>
		/// <param name="num">设备编号</param>
		/// <param name="taskType">任务类型</param>
		/// <returns>记录是否成功</returns>
		private bool StackMemTaskInfo(string deviceTaskNo1, string contNum1, string curNum1, string toNum1,
			string deviceTaskNo2, string contNum2, string curNum2, string toNum2,
			string num, string taskType)
		{
			try
			{
				string setQueue = "MEMQueue";
				string groupName = $"MEM.TC{num}_INFO";

				// 判断是单叉还是双叉任务
				bool isDoubleTask = !string.IsNullOrEmpty(deviceTaskNo2) && !string.IsNullOrEmpty(contNum2);
				string taskDescription = isDoubleTask ? "双叉" : "单叉";

				GZ.Modular.Redis.WriteGroupEntity group = new GZ.Modular.Redis.WriteGroupEntity
				{
					groupName = groupName,
					queueStatus = 1,
					queueTime = DateTime.Now,
					writeList = new List<GZ.Modular.Redis.ParamData>
					{
						// 叉1的数据（单叉和双叉都有）
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_DeviceTaskNo1", paramValue = deviceTaskNo1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_Cont1", paramValue = contNum1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_CurPos1", paramValue = curNum1 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_ToPos1", paramValue = toNum1 ?? "" },

						// 叉2的数据（双叉时有值，单叉时为空）
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_DeviceTaskNo2", paramValue = deviceTaskNo2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_Cont2", paramValue = contNum2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_CurPos2", paramValue = curNum2 ?? "" },
						new GZ.Modular.Redis.ParamData { paramName = $"MEM.TC{num}_ToPos2", paramValue = toNum2 ?? "" },

						// 记录上次执行的任务类型
						new GZ.Modular.Redis.ParamData { paramName = LAST_TASK_TYPE_REDIS_KEY, paramValue = taskType }
					}
				};

				bool result = Conn.YBRedis.SetQueue(group, setQueue, "", "");
				return result;
			}
			catch (Exception ex)
			{
				Conn.YBLog.Error(1, $"[{(string.IsNullOrEmpty(deviceTaskNo2) ? "单叉" : "双叉")}堆垛机MEM记录失败[TC{num}]]", 1, ex.ToString());
				return false;
			}
		}
    }
}
#endregion [自定义类-VS][20250106000000000][DoubleStackerConfirm]